import 'dart:convert';
import 'dart:math';

import 'package:aqua_plunge/dao/broadcaster_dao.dart';
import 'package:aqua_plunge/dao/translate_dao.dart';
import 'package:aqua_plunge/http/app_manager.dart';
import 'package:aqua_plunge/model/common.dart';
import 'package:aqua_plunge/record/sounds_button.dart';
import 'package:aqua_plunge/util/toast_util.dart';
import 'package:aqua_plunge/widget/banner_widget.dart';
import 'package:aqua_plunge/widget/custom_avatar.dart';
import 'package:flutter/material.dart';
import 'package:flutter_util_code/toast_utils.dart';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:get/get.dart';

import '../constants/colors.dart';
import '../controller/DatabaseListController.dart';
import '../model/Author.dart';
import '../model/Creation.dart';
import '../services/database_service.dart';
import '../widget/AudioPlayBar.dart';

class PageDetailPage extends StatefulWidget implements PreferredSizeWidget {
  final int userid;
  final int postid;

  const PageDetailPage({super.key, required this.userid, required this.postid});

  @override
  State<PageDetailPage> createState() => _PageDetailPageState();

  @override
  Size get preferredSize => const Size.fromHeight(56);
}

class _PageDetailPageState extends State<PageDetailPage> {
  Author? author;
  Creation? creation;
  bool speakModel = false;
  final TextEditingController _controller = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  List<Common> commonlist = [];
  String? googlekey;
  final DatabaseService _databaseService = DatabaseService.instance;
  final DatabaseController _databaseListController =
      Get.find<DatabaseController>();
  bool loading = false;

  get appBarview => AppBar(
        centerTitle: false,
        elevation: 0,
        backgroundColor: AppColors.primaryColor,
        leadingWidth: double.infinity,
        actions: [
          GestureDetector(
            onTap: () {
              showModalBottomSheet(
                  context: context,
                  builder: (BuildContext context) {
                    return SingleChildScrollView(
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          Visibility(
                              visible: !(author?.isFriend??false),
                              child: ListTile(
                                  title: const Center(child: Text('Follow')),
                                  onTap: () {
                                    setState(() {
                                      loading = true;
                                    });
                                    BroadCasterDao.addFriend(
                                        int.parse(author!.userId!), () {
                                      _databaseService.updateAuthorFriend(
                                          int.parse(author!.userId!), true);
                                      appToast.showTipLong('Follow Successfully');
                                      setState(() {
                                        author!.isFriend = true;
                                        loading = false;
                                      });
                                      Navigator.pop(context);
                                    });
                                  })),
                          ListTile(
                              title: const Center(
                                child: Text('Block'),
                              ),
                              onTap: () {
                                setState(() {
                                  loading = true;
                                });
                                BroadCasterDao.block(int.parse(author!.userId!),
                                    () {
                                  Navigator.pop(context);
                                  Get.back();
                                  _databaseListController.fetchCreationData();
                                  _databaseListController.fetchMediaData();
                                  appToast.showTipLong('Block Successfully');
                                  setState(() {
                                    loading = false;
                                  });
                                });
                              }),
                          ListTile(
                              title: const Center(
                                child: Text('Report'),
                              ),
                              onTap: () {
                                Navigator.pop(context);
                                _showSecondBottomSheet();
                              }),
                          ListTile(
                              title: const Center(
                                child: Text('Cancel'),
                              ),
                              onTap: () {
                                Navigator.pop(context);
                              }),
                        ],
                      ),
                    );
                  });
            },
            child: Visibility(
              visible: author?.userId != AppManager.getUserInfo().userId,
              child: Image.asset(
                "images/icon_more.png",
                width: 24,
                height: 24,
              ),
            ),
          ),
          const SizedBox(width: 24)
        ],
        leading: Row(
          children: [
            const SizedBox(width: 25),
            GestureDetector(
                child: Image.asset('images/icon_arrow_left.png',
                    width: 23, height: 20),
                onTap: () {
                  Get.back();
                }),
            const SizedBox(width: 18),
            CustomAvatar(width: 42, height: 42, netPath: author?.avatar ?? ''),
            const SizedBox(width: 10),
            Flexible(
                child: Text(
              author?.nickname ?? "",
              maxLines: 1,
              overflow: TextOverflow.clip,
              style: const TextStyle(
                  fontSize: 18,
                  fontWeight: FontWeight.bold,
                  color: Colors.white),
            )),
            const SizedBox(width: 8),
            GestureDetector(
              onTap: () {
                if (author == null) return;
                setState(() {
                  loading = true;
                });
                author!.isFriend!
                    ? BroadCasterDao.unFriend(int.parse(author!.userId!), () {
                        _databaseService.updateAuthorFriend(
                            int.parse(author!.userId!), false);
                        appToast.showTipLong('Unfollow Successfully');
                        _databaseListController.getAuthorByUserId(author!.userId!).then((user) => user.isFriend = false);
                        setState(() {
                          author!.isFriend = false;
                          loading = false;
                        });
                      })
                    : BroadCasterDao.addFriend(int.parse(author!.userId!), () {
                        _databaseService.updateAuthorFriend(
                            int.parse(author!.userId!), true);
                        _databaseListController.getAuthorByUserId(author!.userId!).then((user) => user.isFriend = true);
                        appToast.showTipLong('Follow Successfully');
                        setState(() {
                          author!.isFriend = true;
                          loading = false;
                        });
                      });
              },
              child: Visibility(
                visible: author?.userId != AppManager.getUserInfo().userId,
                child: Image.asset(
                  author?.isFriend ?? false
                      ? 'images/icon_followed.png'
                      : 'images/icon_unfollow.png',
                  width: 38,
                  height: 26,
                ),
              ),
            ),
            const SizedBox(
              width: 50,
            )
          ],
        ),
      );

  get _contentView => CustomScrollView(
    controller: _scrollController,
    physics: const ClampingScrollPhysics(),
        slivers: [
          SliverToBoxAdapter(
              child: Stack(
            children: [
              BannerWidget(
                bannerList: creation?.content ?? [],
                click: (imagepath) {
                  _toggleFullScreen(imagepath);
                },
              ),
              Positioned(
                  right: 24,
                  bottom: 16,
                  child: GestureDetector(
                      onTap: () {
                        _databaseService.updateCreationLike(
                            creation!.postId!, creation?.like == 0 ? 1 : 0);
                        _databaseListController.fetchFavoriteData();
                        _databaseListController.fetchCreationData();
                        setState(() {
                          creation!.like = creation!.like == 0 ? 1 : 0;
                        });
                      },
                      child: Image.asset(
                        creation?.like == 0
                            ? 'images/icon_creation_unlike.png'
                            : 'images/icon_creation_like.png',
                        width: 48,
                        height: 48,
                      )))
            ],
          )),
          SliverToBoxAdapter(
            child: Container(
              padding: const EdgeInsets.fromLTRB(24, 24, 24, 11),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.start,
                children: [
                  Flex(
                    direction: Axis.horizontal,
                    children: [
                      Expanded(
                        child: Text(creation?.title ?? "",
                            textAlign: TextAlign.left,
                            style: const TextStyle(
                                fontSize: 16, color: Colors.white)),
                      )
                    ],
                  ),
                  const SizedBox(
                    height: 12,
                  ),
                  Row(
                    mainAxisSize: MainAxisSize.max,
                    mainAxisAlignment: MainAxisAlignment.start,
                    children: [
                      Expanded(
                          child: Text(
                        creation?.describe ?? "",
                        style: const TextStyle(
                            height: 2,
                            fontSize: 14,
                            color: AppColors.describeColor),
                      ))
                    ],
                  ),
                  Container(
                    alignment: Alignment.centerRight,
                    child: GestureDetector(
                      child: Image.asset(
                        'images/icon_translate.png',
                        width: 20,
                        height: 20,
                      ),
                      onTap: () {
                        if (googlekey == null) {
                          TranslateDao.getGoogleTranslationKey().then((key) {
                            googlekey = key;
                            _translation();
                          });
                        } else {
                          _translation();
                        }
                      },
                    ),
                  )
                ],
              ),
            ),
          ),
          SliverList(
              delegate:
                  SliverChildBuilderDelegate((BuildContext context, int index) {
            return _buildItem(context, index);
          }, childCount: commonlist.length)),
          const SliverPadding(padding: EdgeInsets.only(bottom: 120))
        ],
      );

  get _bottomview => Container(
        padding: const EdgeInsets.fromLTRB(24, 12, 24, 37),
        width: MediaQuery.of(context).size.width,
        color: Colors.black,
        child: Row(
          children: [
            GestureDetector(
              child: Image.asset(
                speakModel
                    ? "images/icon_editable.png"
                    : 'images/icon_speek.png',
                width: 32,
                height: 32,
              ),
              onTap: () {
                setState(() {
                  speakModel = !speakModel;
                });
              },
            ),
            const SizedBox(
              width: 10,
            ),
            Expanded(
                child: speakModel
                    ? SoundsMessageButton(
                        onSendSounds: (type, content) {
                          _postCommon(path: content);
                        },
                      )
                    : Container(
                        decoration: BoxDecoration(
                            color: Colors.white,
                            borderRadius: BorderRadius.circular(30)),
                        padding: const EdgeInsets.only(left: 16),
                        child: TextField(
                            controller: _controller,
                            decoration: const InputDecoration(
                              hintText: 'Enter your ideas...',
                              hintStyle: TextStyle(
                                  color: AppColors.hintColor2, fontSize: 14),
                              border: InputBorder.none,
                            )),
                      )),
            const SizedBox(
              width: 10,
            ),
            GestureDetector(
              child: Image.asset(
                'images/icon_audio_post.png',
                width: 64,
                height: 32,
              ),
              onTap: () {
                speakModel ? _postAudio() : _postCommonCheck();
              },
            )
          ],
        ),
      );

  @override
  void initState() {
    super.initState();
    _loadDatas();
  }

  @override
  void dispose() {
    _controller.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  bool _isImageFluuScreen = false;
  String? _selectImagePath;

  void _toggleFullScreen(String imagePath) {
    setState(() {
      _selectImagePath = imagePath;
      _isImageFluuScreen = !_isImageFluuScreen;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: appBarview,
      body: Container(
        decoration: const BoxDecoration(
            image: DecorationImage(
                image: AssetImage('images/img_mine_bg.png'),
                fit: BoxFit.cover)),
        child: Stack(
          children: [
            _contentView,
            if (_isImageFluuScreen) _showFullImage(),
            Positioned(bottom: 0, child: _bottomview),
            Center(child: Visibility(visible: loading,child: const CircularProgressIndicator(),))
          ],
        ),
      ),
    );
  }

  void _loadDatas() async {
    author = await _databaseService.getAuthorById(widget.userid);
    creation = await _databaseService.getCreationByPostId(widget.postid);
    setState(() {
      if (creation?.common != "") {
        List<dynamic> list = json.decode(creation!.common!);
        commonlist = list.map((json) => Common.fromJson(json)).toList();
      }
    });
  }

  _showFullImage() {
    return Dismissible(
        key: ValueKey(_selectImagePath),
        onDismissed: (direction) {
          setState(() {
            _isImageFluuScreen = false;
          });
        },
        background: Container(
          color: Colors.transparent,
        ),
        child: GestureDetector(
          onTap: () => _toggleFullScreen(_selectImagePath!),
          child: Container(
            padding: const EdgeInsets.only(bottom: 40),
            alignment: Alignment.center,
            height: double.infinity,
            color: AppColors.imagebgColor,
            child: Image.asset(
              _selectImagePath!,
              fit: BoxFit.contain,
            ),
          ),
        ));
  }

  ///发表评论
  _postCommonCheck() {
    _controller.text.isNotEmpty
        ? _postCommon()
        : ToastUtils.showCenter('Cannot send blank comment!');
  }

  _postCommon({String path = ""}) {
    commonlist.add(Common(
        commonId: Random().nextInt(100000) + 1000001,
        avatar: AppManager.getUserInfo().avatarUrl,
        nickname: AppManager.getUserInfo().nickname,
        content: path == "" ? _controller.text.toString() : path,
        like: 0));
    _databaseService.updateCreationCommon(widget.postid, commonlist);
    _controller.clear();
    FocusScope.of(context).unfocus();
    setState(() {});

    WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
      _scrollController.animateTo(_scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300), curve: Curves.easeOut);
    });
  }

  ///发表语音
  _postAudio() {}

  Widget _buildItem(BuildContext context, int index) {
    final Common common = commonlist[index];
    return Container(
      height: 108,
      margin: const EdgeInsets.only(top: 12, left: 24, right: 24),
      width: double.infinity,
      padding: const EdgeInsets.only(left: 12, right: 12, bottom: 12, top: 16),
      decoration: BoxDecoration(
        image: const DecorationImage(
            image: AssetImage('images/list_item_bg.png'), fit: BoxFit.cover),
        borderRadius: BorderRadius.circular(12),
      ),
      child: Row(
        children: [
          Container(
            alignment: Alignment.topLeft,
            child: CustomAvatar(
                width: 40, height: 40, netPath: common.avatar ?? ''),
          ),
          const SizedBox(
            width: 8,
          ),
          Expanded(
              child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Text(
                common.nickname ?? "",
                textAlign: TextAlign.left,
                style: const TextStyle(
                  fontSize: 16,
                  color: AppColors.describeColor,
                  fontWeight: FontWeight.bold,
                ),
              ),
              const SizedBox(
                height: 12,
              ),
              common.content!.endsWith('.m4a')
                  ? AudioPlayBar(audioPath: common.content!)
                  : Text(
                      common.content ?? "",
                      maxLines: 2,
                      textAlign: TextAlign.left,
                      style: const TextStyle(
                          fontSize: 14, color: Colors.white, height: 1.5),
                    ),
            ],
          )),
          Container(
            alignment: Alignment.topRight,
            child: GestureDetector(
              onTap: () {
                commonlist[index].like = common.like == 0 ? 1 : 0;
                _databaseService.updateCreationCommon(
                    widget.postid, commonlist);
                setState(() {});
              },
              child: Image.asset(
                common.like == 0
                    ? 'images/icon_unlike.png'
                    : 'images/icon_liked.png',
                width: 24,
                height: 24,
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _showSecondBottomSheet() {
    showModalBottomSheet(
        context: context,
        builder: (BuildContext context) {
          return SingleChildScrollView(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                _reportItem('Pornographic'),
                _reportItem('False gender'),
                _reportItem('Fraud'),
                _reportItem('Political sensitive'),
                _reportItem('Other'),
                ListTile(
                    title: const Center(
                      child: Text('Cancel'),
                    ),
                    onTap: () {
                      Navigator.pop(context);
                    }),
              ],
            ),
          );
        });
  }

  Widget _reportItem(String complainSub) {
    return ListTile(
        title: Center(child: Text(complainSub)),
        onTap: () {
          setState(() {
            loading = true;
          });
          BroadCasterDao.report(int.parse(author!.userId!), complainSub, () {
            setState(() {
              loading = false;
            });
            Navigator.pop(context);
            Fluttertoast.showToast(
                msg: 'Report Successfully',
                toastLength: Toast.LENGTH_LONG,
                gravity: ToastGravity.CENTER);
          });
        });
  }

  void _translation() async {
    await TranslateDao.translate(context, googlekey ?? "", 'hello');
  }
}
